package com.lianzhihui.romeex.ui.trade.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.tabs.TabLayout;
import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.adapter.FilterAdapter;
import com.lianzhihui.romeex.adapter.MyFragmentAdapter;
import com.lianzhihui.romeex.bean.FlowCellBean;
import com.lianzhihui.romeex.config.MessageEvent;
import com.lianzhihui.romeex.inter.DialogListener;
import com.lianzhihui.romeex.mvp.presenter.FlowCellInfoPresenter;
import com.lianzhihui.romeex.mvp.presenter.PledgePresenter;
import com.lianzhihui.romeex.mvp.view.FlowCellView;
import com.lianzhihui.romeex.mvp.view.PledgeView;
import com.lianzhihui.romeex.net.APIConstant;
import com.lianzhihui.romeex.ui.base.BaseFragment;
import com.lianzhihui.romeex.ui.base.CustomWebActivity;
import com.lianzhihui.romeex.ui.trade.adapter.FlowCellFragmentAdapter;
import com.lianzhihui.romeex.utils.MathUtil;
import com.lianzhihui.romeex.utils.NumberUtils;
import com.lianzhihui.romeex.widget.MyViewPager;
import com.lianzhihui.romeex.widget.dialog.ExtractDialog;
import com.lianzhihui.romeex.widget.dialog.PledgeDialog;
import com.lianzhihui.romeex.widget.dialog.PledgeSucDialog;
import com.lianzhihui.romeex.widget.keybord.CustomPopWindow;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

import static com.lianzhihui.romeex.config.AppConstants.Event.END_REFRESH_FLOWCELL;
import static com.lianzhihui.romeex.config.AppConstants.Event.REFRESH_PLEDGE;

/**
 * ProjectName: romeex
 * Package: com.lianzhihui.romeex.ui.trade.fragment
 * ClassName: ExtractFragment
 * Description: 流动池
 * Author: zhanghong
 * CreateDate: 2020/10/30 14:39
 * UpdateUser: 更新者：
 * UpdateDate: 2020/10/30 14:39
 * UpdateRemark: 更新说明：
 * Version: 1.0
 */
public class FlowCellFragment extends BaseFragment implements TabLayout.OnTabSelectedListener, FlowCellView, PledgeView, OnRefreshListener {

    @BindView(R.id.refresher)
    SmartRefreshLayout refresher;
    @BindView(R.id.label_title)
    TextView labelTitle;
    @BindView(R.id.icon_rusd)
    ImageView iconRusd;
    @BindView(R.id.tv_rusd)
    TextView tvRusd;
    @BindView(R.id.input_layout)
    RelativeLayout inputLayout;
    @BindView(R.id.icon_plus)
    ImageView iconPlus;
    @BindView(R.id.icon_ret)
    ImageView iconRet;
    @BindView(R.id.tv_ret)
    TextView tvRet;
    @BindView(R.id.tv_input)
    TextView tv_input;
    @BindView(R.id.input_layout_two)
    RelativeLayout inputLayoutTwo;
    @BindView(R.id.left_count)
    TextView left_count;
    @BindView(R.id.right_count)
    TextView right_count;
    @BindView(R.id.tv_res)
    TextView tv_res;
    @BindView(R.id.take_out)
    TextView takeOut;
    @BindView(R.id.tv_pledge)
    TextView tvPledge;
    @BindView(R.id.tv_take_out)
    TextView tvTakeOut;
    @BindView(R.id.click_show)
    TextView click_show;
    @BindView(R.id.iv_filter)
    ImageView iv_filter;
    @BindView(R.id.header_layout)
    RelativeLayout headerLayout;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.mViewPager)
    MyViewPager mViewPager;
    @BindView(R.id.layout_root)
    RelativeLayout layout_root;

    FlowCellInfoPresenter infoPresenter;
    PledgePresenter pledgePresenter;
    FilterAdapter filterAdapter;
    FilterAdapter filterAdapter2;
    FlowCellBean config;
    int destroy = 0;

    ArrayList<Fragment> fragmentList = new ArrayList<>();
    String filterStr = "";
    String selectStr = "全部";
    String filterStr2 = "";
    String selectStr2 = "全部";

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_flow_cell;
    }

    @Override
    protected void initView() {

        infoPresenter = new FlowCellInfoPresenter(activity, this);
        pledgePresenter = new PledgePresenter(activity, this);

        fragmentList.add(new PledgeFragment());
        fragmentList.add(new ExtractFragment());
        FragmentManager fragmentManager = getChildFragmentManager();
        MyFragmentAdapter adapter = new MyFragmentAdapter(fragmentManager, fragmentList);
        mViewPager.setScrollable(false);
        mViewPager.setOffscreenPageLimit(2);
        mViewPager.setAdapter(adapter);
        tabLayout.addOnTabSelectedListener(this);
        refresher.setOnRefreshListener(this);
        infoPresenter.getFLInfo();
        this.filterAdapter = new FilterAdapter();
        this.filterAdapter2 = new FilterAdapter();
    }

    /**
     * 质押过滤
     */
    private void showPledgeFilter() {

        ArrayList<String> list = new ArrayList<>();
        list.add("全部");
        list.add("排队中");
        list.add("重新排队");
        list.add("收益中");
        list.add("已结束");
        filterAdapter.setSelectStr(selectStr);
        filterAdapter.setNewData(list);
        View view = getLayoutInflater().inflate(R.layout.popup_def_layout, null);
        CustomPopWindow popWindow = new CustomPopWindow.PopupWindowBuilder(activity)
                .setView(view)//显示的布局，还可以通过设置一个View
                //     .size(600,400) //设置显示的大小，不设置就默认包裹内容
                .setFocusable(true)//是否获取焦点，默认为ture
                .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                .create()//创建PopupWindow
                .showAsDropDown(iv_filter, 0, 0);//显示PopupWindow

        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(filterAdapter);
        filterAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                PledgeFragment fragment = (PledgeFragment) fragmentList.get(0);
                selectStr = filterAdapter.getItem(position);
                switch (position) {
                    case 0:
                        filterStr = "-1";
                        break;
                    case 1:
                        filterStr = "1";
                        break;
                    case 2:
                        filterStr = "3";
                        break;
                    case 3:
                        filterStr = "2";
                        break;
                    case 4:
                        filterStr = "4";
                        break;
                }
                fragment.setStatus(filterStr);
                popWindow.dissmiss();
            }
        });

    }

    /**
     * 提取过滤
     */
    private void showExtractFilter() {

        ArrayList<String> list = new ArrayList<>();
        list.add("全部");
        list.add("已提取");
        list.add("已取消");
        filterAdapter2.setSelectStr(selectStr2);
        filterAdapter2.setNewData(list);
        View view = getLayoutInflater().inflate(R.layout.popup_def_layout, null);
        CustomPopWindow popWindow = new CustomPopWindow.PopupWindowBuilder(activity)
                .setView(view)//显示的布局，还可以通过设置一个View
                //     .size(600,400) //设置显示的大小，不设置就默认包裹内容
                .setFocusable(true)//是否获取焦点，默认为ture
                .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                .create()//创建PopupWindow
                .showAsDropDown(iv_filter, 0, 0);//显示PopupWindow

        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(filterAdapter2);
        filterAdapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ExtractFragment fragment = (ExtractFragment) fragmentList.get(1);
                selectStr2 = filterAdapter2.getItem(position);
                switch (position) {
                    case 0:
                        filterStr2 = "-1";
                        break;
                    case 1:
                        filterStr2 = "5";
                        break;
                    case 2:
                        filterStr2 = "6";
                        break;
                }
                fragment.setStatus(filterStr2);
                popWindow.dissmiss();
            }
        });

    }

    @SuppressLint("SetTextI18n")
    private void count() {
        if (config == null) {
            return;
        }
        double count = Double.parseDouble(tv_input.getText().toString());
        double percent = MathUtil.multiply(count, 0.3);
        double res = MathUtil.multiply(percent, config.getPrice());
        tv_res.setText(NumberUtils.big8(res));
        //是否第一次
        if (config.getIsFirsetPledge() == 1) {
            //第一次
            destroy = 0;
            left_count.setText("0 " + getString(R.string.text_rex));
        } else {
            //不是第一次
            for (FlowCellBean.StageDestroyBean item : config.getStageDestroy()) {
                if (count <= item.getStage()) {
                    left_count.setText(item.getDestroyNum() + " " + getString(R.string.text_rex));
                    destroy = item.getDestroyNum();
                    break;
                }
            }
        }
    }

    private void pledge() {

        String valuestr = tv_input.getText().toString();

        showLoading("");
        if (config == null) {
            infoPresenter.getFLInfo();
        } else {
            pledgePresenter.pledge(valuestr);
        }
    }

    private void extract() {
        showLoading("");
        pledgePresenter.extract();
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onFLInfo(FlowCellBean bean) {
        dismissLoading();
        //配置数据
        config = bean;
        right_count.setText(NumberUtils.big8(config.getMyBalance()) + " " + getString(R.string.text_rex));
        count();
    }

    @Override
    public void onFLInfoFail(String message) {
        dismissLoading();
        if (isAdded()) {
            toast(getString(R.string.get_data_fail));
        }
    }

    @Override
    public void setFailure() {

    }

    @Override
    public void onPledgeSuccess() {
//        toast("质押成功");
        dismissLoading();
        PledgeSucDialog psDialog = new PledgeSucDialog(activity);
        psDialog.show();
        refresher.autoRefresh();
    }

    @Override
    public void onPledgeFail(String message) {
        dismissLoading();
        toast(message);
    }

    @Override
    public void onExtractSuccess() {
        PledgeSucDialog psDialog = new PledgeSucDialog(activity);
        psDialog.setTitle(getString(R.string.extract_success));
        psDialog.show();
        dismissLoading();
        refresher.autoRefresh();
    }

    @Override
    public void onExtractFail(String message) {
        dismissLoading();
        toast(message);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        infoPresenter.getFLInfo();
        int position = mViewPager.getCurrentItem();
        if (position == 0) {
            PledgeFragment fragment = (PledgeFragment) fragmentList.get(position);
            fragment.refresh();
        } else {
            ExtractFragment fragment = (ExtractFragment) fragmentList.get(position);
            fragment.refresh();
        }
    }

    @Override
    public void onMessageEvent(MessageEvent event) {
        super.onMessageEvent(event);
        if(event.getCode() == END_REFRESH_FLOWCELL){
            refresher.finishRefresh();
        }
        if(event.getCode() == REFRESH_PLEDGE){
            refresher.autoRefresh();
        }
    }

    @OnClick({R.id.input_layout, R.id.click_show, R.id.tv_pledge, R.id.tv_take_out, R.id.trade_rule, R.id.iv_filter})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.input_layout:
            case R.id.click_show:
                @SuppressLint("InflateParams") View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.pop_usdt_list, null, false);
                PopupWindow popupBigPhoto = new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
                RecyclerView viewById = inflate.findViewById(R.id.myRecyclerView);
                popupBigPhoto.setOutsideTouchable(true);
                GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
                viewById.setLayoutManager(gridLayoutManager);
                ArrayList<String> strings = new ArrayList<>();
                strings.add("100");
                strings.add("200");
                strings.add("300");
                strings.add("400");
                strings.add("500");
                strings.add("600");
                strings.add("700");
                strings.add("800");
                strings.add("900");
                strings.add("1000");
                FlowCellFragmentAdapter adapter = new FlowCellFragmentAdapter(getActivity(), strings);
                adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        tv_input.setText((String) adapter.getItem(position));
                        //计算 RET
                        count();
                        popupBigPhoto.dismiss();
                    }
                });
                adapter.setSelectStr(tv_input.getText().toString());
                viewById.setAdapter(adapter);

                popupBigPhoto.showAsDropDown(click_show, 0, 20);
                break;
            case R.id.tv_pledge:

                String valuestr = tv_input.getText().toString();
                if (valuestr.equals("0")) {
                    toast(getString(R.string.warning_select_pledge_num));
                    return;
                }
//                double value = Double.parseDouble(valuestr);
//
//                if (value + destroy > config.getMyBalance()) {
//                    toast("超出余额");
//                    return;
//                }
                if (null != config) {
                    PledgeDialog dialog = new PledgeDialog(activity);

                    dialog.setText(config.getIsFirsetPledge(), valuestr, tv_res.getText().toString(), destroy + "");
                    dialog.setListener(new DialogListener() {
                        @Override
                        public void onPassed() {
                            pledge();
                        }

                        @Override
                        public void onFail() {

                        }
                    });

                    dialog.show();
                }

                break;
            case R.id.tv_take_out:

                if (config == null) {
                    return;
                }

                if (config.getCanExtract() != 1) {
                    toast("不可提取");
                    return;
                }

                ExtractDialog dialog2 = new ExtractDialog(activity);
                dialog2.setText(config);
                dialog2.setListener(new DialogListener() {
                    @Override
                    public void onPassed() {
                        extract();
                    }

                    @Override
                    public void onFail() {

                    }
                });
                dialog2.show();

                break;
            case R.id.iv_filter:
                //过滤器

                int position = tabLayout.getSelectedTabPosition();

                if (position == 0) {
                    showPledgeFilter();
                } else {
                    showExtractFilter();
                }
                break;
            case R.id.trade_rule:

                Intent intent1 = new Intent(activity, CustomWebActivity.class);
                intent1.putExtra("url", APIConstant.H5_trade_rule);
                intent1.putExtra("title", getString(R.string.trade_rule));
                intent1.putExtra("isHideTitle", false);
                startActivity(intent1);

                break;
            default:
                break;
        }
    }


}